package cn.hotel.Listener;

import cn.hotel.entity.Order;
import cn.hotel.event.OrderCreateEvent;
import cn.hotel.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 创建一个监听器用来监听订单创建事件
 */
@Slf4j
@Component
public class OrderCreateListener implements ApplicationListener<OrderCreateEvent> {

    @Autowired
    private OrderService orderService;

    @Override
    public void onApplicationEvent(OrderCreateEvent event) {
        Order order = event.getOrder();
        Timer timer = new Timer();
        Integer orderId = order.getOrderId();
        timer.schedule(new TimerTask() {
            public void run() {
                Order orderById = orderService.getOrderById(orderId);
                //0表示未支付
                if (orderById!=null&&orderById.getOrderStatus()==0){
                    log.info("删除订单==={}",orderById);
                    orderService.cancelOrder(orderId);
                }
            }
        }, 15*60*1000); // 15分钟
    }
}
